<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 搜索区 -->
      <el-form :inline="true" class="demo-form-inline" label-width="80px">
        <el-row>
          <el-col :span=22>
            <el-form-item label="目录名称">
              <el-input v-model="searchForm.direcName"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.direcState" placeholder="请选择">
                <el-option v-for="item in stateList" :key="item.state" :label="item.desc" :value="item.state"></el-option>
              </el-select>
            </el-form-item>
            <!-- 按钮区 -->
            <el-form-item>
              <el-button size="small" @click="handleClear">清除</el-button>
              <el-button type="primary" size="small" @click="searchDirec">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span=2>
            <el-form-item >
              <el-button @click="addBtn"  type="success" size="small" >
                <i class="el-icon-edit"></i>
                新增目录
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据总数 -->
      <TotalDirec>
        <span>数据表一共{{total}}条</span>
      </TotalDirec>
      <!-- 数据列表区 -->
      <el-table
        ref="tableRef"
        :data="subDirec"
        style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          >
        </el-table-column>
        <el-table-column
          prop="subjectName"
          label="所属学科"
          >
        </el-table-column>
        <el-table-column
          prop="directoryName"
          label="目录名称"
          >
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者">
        </el-table-column>
        <el-table-column
          prop="addDate"
          label="创建日期">
          <template v-slot="{row}">
            {{formatDate(row.addDate)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="totals"
          label="面试题数量">
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态">
          <template v-slot="{row}">
            {{row.state===1 ? '已启用':'已禁用'}}
            <!-- {{formatState(row)}} -->
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="操作">
          <!-- <template #slot="{row}"> -->
          <template v-slot="{row}">
            <el-button type="text" @click="switchState(row)">{{row.state === 1 ? '启用' :'禁用'}}</el-button>
            <el-button type="text" :disabled="row.state===1" @click="handleEdit(row)">修改</el-button>
            <el-button type="text" :disabled="row.state===1" @click="handleDel(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        hide-on-single-page
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5,10,20,30]"
        :page-size="queryDirec.pagesize"
        :current-page="queryDirec.page"
        :total="total"
        layout="->, prev, pager, next, sizes, jumper"
      >
      </el-pagination>
    </el-card>
    <!-- 新增、修改目录的弹出层 -->
    <el-dialog :title="title.type" :visible.sync="addVisible" width="30%" :before-close="handleClose">
      <el-form :model="addForm" :rules="addRules" ref="addRef">
        <el-form-item label="所属学科" prop="subjectID" size="small">
          <el-select v-model="addForm.subjectID" placeholder="请选择" class="dicwid" >
            <el-option v-for="item in simpleSub" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName" size="small">
          <el-input v-model="addForm.directoryName" placeholder="请输入目录名称" class="dicwid" ></el-input>
        </el-form-item>
      </el-form>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addDirec">确 定</el-button>
    </el-dialog>
  </div>
</template>
<script>
import { list, add, simple, remove, detail, update, changeState } from '@/api/hmmm/directorys.js'
import TotalDirec from '@/components/TotalDirec/indev.vue'
import dayjs from 'dayjs'
export default {
  components: { TotalDirec },
  data () {
    return {
      // 标题
      title: {
        type: null
      },
      // 添加、修改表单
      addForm: {
        subjectID: null,
        directoryName: ''
      },
      // 验证规则
      addRules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: ['blur', 'change'] }],
        directoryName: [
          { required: true, message: '清输入标签名称', trigger: ['blur', 'change'] }]
      },
      // 弹出层标志位
      addVisible: false,
      // 所有数据状态
      stateList: [
        { state: 0, desc: '禁用' },
        { state: 1, desc: '启用' }
      ],
      // 页面显示,注意：每次切换页码或者切换每页显示多少条数时，都会重新发送请求，刷新页面
      queryDirec: {
        page: 1,
        pagesize: 10
      },
      // 学科目录
      subDirec: [],
      // 简单学科目录
      simpleSub: [],
      // 目录总数
      total: 0,
      // 搜索表单
      searchForm: {
        direcName: '',
        direcState: null
      }
    }
  },
  created () {
    // 加载目录列表
    this.loadDirec()
    // 加载学科列表
    this.getSimpleSub()
  },
  methods: {
    // 格式化时间
    formatDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 切换每页显示多少条数据
    handleSizeChange (pagesize) {
      this.queryDirec.pagesize = pagesize
      // 重置显示第一页
      this.queryDirec.page = 1
      this.loadDirec()
    },
    // 切换当前页码
    handleCurrentChange (page) {
      this.queryDirec.page = page
      // 加载列表
      this.loadDirec()
    },
    // 搜索
    async searchDirec () {
      const ret = await list(this.queryDirec = {
        ...this.queryDirec,
        directoryName: this.searchForm.direcName,
        state: this.searchForm.direcState
      })
      this.subDirec = ret.data.items
      this.loadDirec()
    },
    // 切换状态
    async switchState (row) {
      try {
        await changeState({
          id: row.id,
          state: row.state
        })
        // console.log(ret)
        row.state = row.state === 1 ? 0 : 1
        this.$message.success('切换状态成功')
      } catch {
        this.$message.error('切换状态失败')
      }
    },
    // 清除
    handleClear () {
      this.searchForm.direcName = ''
      this.searchForm.direcState = null
    },
    // 删除目录
    async handleDel (row) {
      console.log(row)
      // 弹窗询问
      const delRet = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (delRet === 'confirm') {
        try {
          const ret = await remove(row)
          if (ret.status === 200) {
          // 删除优化：当前页面加载回来的数据只有一条，并且当前页码>1时，删除之后默认显示上一页数据
            if (this.subDirec.length === 1 && this.queryDirec.page > 1) {
              this.queryDirec.page--
              // 重新加载列表
              this.loadDirec()
            }
          } else {
            this.$message.error('删除目录失败')
          }
        } catch {
          this.$message.error('删除目录失败')
        }
      }
    },
    // 关闭弹出层之前的回调
    handleClose () {
      this.addVisible = false
      // 重置表单
      this.$refs.addRef.resetFields()
    },
    // 新增目录(定制标题、显示弹出层)
    addBtn () {
      this.addVisible = true
      this.title.type = '添加目录'
    },
    // 编辑目录
    async handleEdit (row) {
      this.addVisible = true
      this.title.type = '修改目录'
      const ret = await detail(row)
      if (ret.status === 200) {
        // 数据回显
        this.addForm = ret.data
        // 重新收集数据，验证表单，提交
        const subRet = await update(this.addForm)
        console.log(subRet)
      } else {
        this.$message.error('获取目录失败')
      }
    },
    // 确认添加
    addDirec () {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        // 校验通过，调接口
        const ret = await add(this.addForm)
        console.log(ret)
        // 关闭弹出层
        this.addVisible = false
        // 重置表单
        this.$refs.addRef.resetFields()
        // 从新加载列表
        this.loadDirec()
      })
    },
    // 加载简单学科目录
    async getSimpleSub () {
      const ret = await simple()
      this.simpleSub = ret.data
      // console.log(ret)
    },
    // 加载目录列表
    async loadDirec () {
      const ret = await list(this.queryDirec)
      console.log(ret)
      if (ret.status !== 200) return this.$message('获取学科目录失败')
      this.total = ret.data.counts // 总数
      this.subDirec = ret.data.items // 目录数据
    }
  }
}
</script>

<style scoped lang='scss'>
.box-card {
  margin: .625rem .625rem 0 .625rem;
  padding-left:.625rem
}
.total{
  width: 100%;
  background-color: #ccc;
}
.dicwid{
  width: 263px;
}
.dialog-footer{
 padding-right: 200px;
}
</style>
